/**
 * 数据交互类
 */
const hook2global = global.__proto__ || global
import exchange from '@service.exchange'
import config from '../../config'
import data from './data'
export default class ExChange {
  constructor(app) {
    this.$app=app
    this.$def=app.$def
    this.data=data
    this.sign=''
  }
  /**
   * 
   * @param {*} key  存储数据 key
   * @param {*} callback  回调
   */
  get(key,callback){
    // console.log("=====",config.sign,config.pkg)
    let timer=null
    exchange.get({
      sign:config.sign,
      package:config.pkg,
      // scope:"global",
      key: key,
      success:res=> {
        let value=res&&res.value?res.value:res
        if(!value) return
        clearTimeout(timer)
        if(value){
          try{
            if(value.indexOf(':')==-1){
              callback(value) 
            }else{
              callback(JSON.parse(value))
            }
          }catch(err){
            callback(value)
          } 
        }else{
          callback(value)
        }
      },
      fail:(error, code)=> {
        console.log('获取数据失败:',error,code)
        let data={
          code:code,
          data:error
        }
        callback&&callback(data) 
      }
    })
    timer=setTimeout(()=>{
      hook2global.$storage.getItem(key,res=>{
        callback&&callback(res)
      })
    },4000)
  }
  /**
   * 
   * @param {String} key 
   * @param {Object} value 
   */
  set(key,value,callback){
    let data=value
    if(typeof data != 'string'){
      data=JSON.stringify(data)
    }
    exchange.set({
      key: key,
      value: data,
      // scope:"global",
      sign:config.sign,
      package:config.pkg,
      success: ()=> {
        callback&&callback()
      },
      fail: (data, code)=> {
        console.log(`exchange ${key} set fail, code = ${code}`,JSON.stringify(data))
      }
    })
  }
  /**
   * 
   * @param {*} key  移除
   */
  remove(key){
    exchange.remove({
      key: key,
      success: function() {
        console.log(`exchange remove ${key} success`)
      },
      fail: function(data, code) {
        console.log(`exchange remove ${key} fail ${JSON.stringify(data)}${code}`)
      }
    })
  }
  /**
   * 清除所有数据
   * @param {*} callback  回调
   */
  
  clear(callback){
    exchange.clear({
      success: ()=> {
        callback&&callback(1)
      },
      fail: function(data, code) {
        callback&&callback(0)
      }
    })
  }
}